package com.ad.blogger.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import com.ad.blogger.dao.impl.WeiboManageDAOImpl;
import com.ad.blogger.entity.WeiboAccounts;
import com.ad.blogger.service.IWeiboManageService;
import com.ad.common.action.BaseActionSupport;
import com.ad.common.entity.User;
import com.ad.common.utils.StringUtils;

public class WeiboManageAction extends BaseActionSupport{
	private final Log logger = LogFactory.getLog(getClass()); 
	public static String SEARCH_URL_SINA = "http://s.weibo.com/user/&nickname=${queryStr}&Refer=SUer_box";
	public static String SEARCH_URL_QQ = "http://t.qq.com/${queryStr}";
	private static final long serialVersionUID = 1L;
	private IWeiboManageService weiboManageService ;
	private List<WeiboAccounts> weiboAccounts;
	/**
	 * 根据微博某项查询时用到的
	 */
	private WeiboAccounts weibo;
	/**
	 * 微博管理页
	 */
	public static final String WB_MANAGE="wbManage";
	
	public String wbManage() throws Exception{
		logger.debug("wbManage...");
		User user = (User) this.getSessionMap().get("b_user");
		if(user!=null){
			List<WeiboAccounts> weibos = weiboManageService.getWeiboAccountsByUserId(user.getId());
			this.setWeiboAccounts(weibos);
			logger.debug("get weibos size="+weibos.size());
		}else{
			return INPUT;
		}
		return WB_MANAGE ;
	}
	
	public String searchByName() throws Exception{
		User user = (User) this.getSessionMap().get("b_user");
		if(user!=null){
			List<WeiboAccounts> weibos = weiboManageService.getWeiboByAccountName(user.getId(), weibo.getNickname());
			this.setWeiboAccounts(weibos);
			logger.debug("get weibos size="+weibos.size());
		}else{
			return INPUT;
		}
		
		
		return WB_MANAGE;
	}
	public String addWeiboAccount() throws Exception{
		String nickname = weibo.getNickname();
		if(weibo==null || StringUtils.isEmpty(nickname)){
			
		}else{
			WeiboAccounts weiboAccounts = initAccount();
			 if(weiboAccounts!=null){
		    	  this.weiboManageService.save(weiboAccounts);
		      }
		}
		return WB_MANAGE;
	}
	
	public WeiboAccounts initAccount(){
		int platform = weibo.getPlatform();
		String nickname = weibo.getNickname();
		String url = null ;
		switch(platform){
		case 1:
			try {
				url = SEARCH_URL_SINA.replace("${queryStr}", URLEncoder.encode(nickname,"UTF-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			break;
		case 2:
			url = SEARCH_URL_QQ.replace("${queryStr}", nickname);
			break;
		}
		if(url!=null){
	      String responseBody = this.getStringFromUrl(url);
	      WeiboAccounts weiboAccounts = this.weiboManageService.parseWeiboAccountsFromContent(platform, nickname, responseBody);
	      weiboAccounts.setUser((User) this.getSessionMap().get("b_user"));
	      weiboAccounts.setPriceDirect(weibo.getPriceDirect());
	      weiboAccounts.setPriceTransmit(weibo.getPriceTransmit());
	      return weiboAccounts ;
		}
		return null ;
	}
	public String getStringFromUrl(String url){
		logger.debug("add weibo url="+url);
        HttpClient httpclient = new DefaultHttpClient();
        String responseBody = null ;
        try {
            HttpGet httpget = new HttpGet(url);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            responseBody = httpclient.execute(httpget, responseHandler);
        	responseBody = responseBody.replaceAll("\\\\\"", "\"");
        	responseBody = responseBody.replaceAll("\\\\/", "/");
        	responseBody = responseBody.replaceAll("\\\\t", "");
        	responseBody = responseBody.replaceAll("\\\\n", "");
        } catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		} catch (ClientProtocolException e) {
			logger.error(e.getMessage());
		} catch (IOException e) {
			logger.error(e.getMessage());
		} finally {
            httpclient.getConnectionManager().shutdown();
        }
		return responseBody;
	}
	public IWeiboManageService getWeiboManageService() {
		return weiboManageService;
	}
	public void setWeiboManageService(IWeiboManageService weiboManageService) {
		this.weiboManageService = weiboManageService;
	}
	public List<WeiboAccounts> getWeiboAccounts() {
		return weiboAccounts;
	}
	public void setWeiboAccounts(List<WeiboAccounts> weiboAccounts) {
		this.weiboAccounts = weiboAccounts;
	}

	public WeiboAccounts getWeibo() {
		return weibo;
	}

	public void setWeibo(WeiboAccounts weibo) {
		this.weibo = weibo;
	}
}
